package com.example.demo.validation;

import java.io.Serializable;
import java.util.Iterator;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

/**
* @comments
* @author  zg
* @date 2018年8月28日 
*/
public class DtoValidator <T> implements Serializable{
	private static final long serialVersionUID = 1L;
	
	private static ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
	
	/**
	 * 校验属性值-最小检验，有错误即返回
	* @author zg
	* @date 2018年8月28日
	* @return 返回null表示没有错误
	 */
	public String validate(){
		String msg = null;
		Iterator<ConstraintViolation<DtoValidator<T>>> iterator = getViolationsIterator();
		if(iterator.hasNext()){
			msg = iterator.next().getMessage();
		}
		return msg;
	}

	private Iterator<ConstraintViolation<DtoValidator<T>>> getViolationsIterator(){
		Validator validator = factory.getValidator();
		Set<ConstraintViolation<DtoValidator<T>>> violations = validator.validate(this);
		Iterator<ConstraintViolation<DtoValidator<T>>> iterator = violations.iterator();
		return iterator;
	}
	
}
